package com.lxl.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

/**
 * @author 北上寻海
 */
@WebFilter(filterName = "charsetFilter",urlPatterns = "/*",
initParams = {@WebInitParam(name="characterEncoding",value = "utf-8")})
public class CharsetFilter implements Filter {
    private FilterConfig filterConfig;
    private String characterEncoding;
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        //将所有路径拦截了，在这里进行字符编码设置
            if(null!=characterEncoding){
                request.setCharacterEncoding(characterEncoding);
                response.setCharacterEncoding(characterEncoding);
            }
             chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        /*初始化方法  接收一个FilterConfig类型的参数 该参数是对Filter的一些配置*/

        this.filterConfig = config;
        characterEncoding = this.filterConfig.getInitParameter("characterEncoding");
    }

}
